package com.chenxy.common.controller;

import com.chenxy.common.exception.bean.BaseExceptionBean;
import com.chenxy.common.exception.impl.CommonException;
import com.chenxy.common.exception.impl.CommonExceptionEnum;
import com.chenxy.common.result.Res;
import org.springframework.boot.autoconfigure.klock.handler.KlockTimeoutException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Controller公共基类
 * @author chenxy
 */
public class BaseController {

    // 这些对象何以直接被子类使用
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected HttpSession session;

    @ModelAttribute
    public void setReqAndRes(HttpServletRequest req, HttpServletResponse res) {
        this.request = req;
        this.response = res;
        this.session = req.getSession();
    }

    protected Integer getUserId(){
        String userId = request.getHeader("userid");
        Integer userid = Integer.valueOf(userId);
        return userid;
    }


    /**
     * 统一异常拦截，针对springboot
     * @param request
     * @param exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Res<BaseExceptionBean> handlerException(HttpServletRequest request, Exception exception){
        BaseExceptionBean baseExceptionBean = new BaseExceptionBean();
        if(exception instanceof CommonException){
            CommonException commonException = (CommonException) exception;
            baseExceptionBean.setErrCode(commonException.getErrCode());
            baseExceptionBean.setErrMsg(commonException.getErrMsg());
            return Res.create(commonException.getErrCode(),Res.FAIL, commonException.getErrMsg());
        }
        if(exception instanceof KlockTimeoutException){
            return Res.create(CommonExceptionEnum.REPEAT_REQUEST_ERROR.getErrCode(),
                    Res.FAIL, CommonExceptionEnum.REPEAT_REQUEST_ERROR.getErrMsg());
        }
        return Res.create(CommonExceptionEnum.UNKNOWN_ERROR.getErrCode(),
                Res.FAIL, CommonExceptionEnum.UNKNOWN_ERROR.getErrMsg());
    }

}
